<template>
  <div class="chart-container">
    <!-- 控制面板 -->
    <div class="control-panel">
      <div class="control-group">
        <span class="control-label">显示内容：</span>
        <el-button
          :type="showType === 'equipment' ? 'primary' : 'default'"
          @click="switchShowType('equipment')"
          size="small"
        >
          设备状态
        </el-button>
<!--        <el-button-->
<!--          :type="showType === 'supply' ? 'primary' : 'default'"-->
<!--          @click="switchShowType('supply')"-->
<!--          size="small"-->
<!--        >-->
<!--          耗材数量-->
<!--        </el-button>-->
        <el-button
          :type="showType === 'fault' ? 'primary' : 'default'"
          @click="switchShowType('fault')"
          size="small"
        >
          故障统计
        </el-button>
      </div>

      <div class="control-group">
        <span class="control-label">图表类型：</span>
        <el-button
          :type="chartType === 'bar' ? 'primary' : 'default'"
          @click="switchChartType('bar')"
          size="small"
          :disabled="showType === 'fault'"
        >
          柱状图
        </el-button>
        <el-button
          :type="chartType === 'pie' ? 'primary' : 'default'"
          @click="switchChartType('pie')"
          size="small"
          :disabled="showType === 'fault'"
        >
          饼图
        </el-button>
      </div>
    </div>
    <!-- 故障统计筛选卡片 -->
    <div v-if="showType === 'fault'" class="filter-card">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>筛选条件</span>
        </div>
        <div class="filter-content">
          <el-cascader
            v-model="selectedBrandModel"
            :options="brandModelOptions"
            :props="{ expandTrigger: 'hover', changeOnSelect: true }"
            placeholder="请选择品牌和型号"
            clearable
          ></el-cascader>
          <el-button type="primary" @click="filterByBrandModel">筛选</el-button>
        </div>
      </el-card>
    </div>
    <!-- 图表区域 -->
    <div class="chart-wrapper">
      <!-- 添加加载状态指示器 -->
      <div v-if="!dataLoaded" class="loading-container">
        <div class="loading-spinner"></div>
        <p>数据加载中...</p>
      </div>

      <!-- 只有在数据加载完成后才显示图表 -->
      <div v-else>
        <div v-if="showType !== 'fault'" ref="mainChart" class="chart"></div>

        <!-- 故障统计区域 -->
        <div v-else class="fault-statistics-container">
          <!-- 故障率统计 -->
          <div class="fault-rate-section">
            <!--          <h3>全院设备故障率统计</h3>-->
            <!--          <div ref="faultRateChart" class="fault-rate-chart"></div>-->
          </div>

          <!-- 品牌/型号故障率对比 -->
          <div class="brand-fault-section">
            <!--          <h3>同品牌/型号设备故障率对比</h3>-->
            <!--          <div class="brand-fault-content">-->
            <!--            <div ref="brandFaultChart" class="brand-fault-chart"></div>-->
            <!--            <div class="brand-fault-table">-->
            <!--              <el-table :data="brandFaultData" style="width: 100%" stripe>-->
            <!--                <el-table-column prop="brand" label="品牌" width="120"></el-table-column>-->
            <!--                <el-table-column prop="model" label="型号" width="150"></el-table-column>-->
            <!--                <el-table-column prop="totalCount" label="设备总数" width="100"></el-table-column>-->
            <!--                <el-table-column prop="faultCount" label="故障次数" width="100"></el-table-column>-->
            <!--                <el-table-column prop="faultRate" label="故障率(%)" width="120">-->
            <!--                  <template slot-scope="scope">-->
            <!--                    {{ scope.row.faultRate }}%-->
            <!--                  </template>-->
            <!--                </el-table-column>-->
            <!--                <el-table-column label="排名" width="80">-->
            <!--                  <template slot-scope="scope">-->
            <!--                    <span :class="getRankClass(scope.$index + 1)">-->
            <!--                      {{ scope.$index + 1 }}-->
            <!--                    </span>-->
            <!--                  </template>-->
            <!--                </el-table-column>-->
            <!--              </el-table>-->
            <!--            </div>-->
            <!--          </div>-->
          </div>

          <!-- 故障类型占比 -->
          <div class="fault-type-section">
            <h3>故障类型占比分析</h3>
            <div ref="faultTypeChart" class="fault-type-chart"></div>
          </div>

          <!-- 月故障率趋势统计 -->
          <div class="monthly-fault-rate-section">
            <h3>月故障率趋势统计</h3>
            <div ref="monthlyFaultRateChart" class="monthly-fault-rate-chart"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {
  getAllAssetBrandAndModelSpec,
  getEquipmentData,
  getFaultTypeData,
  getMonthlyFaultRateData
} from "@/api/equ/count";

export default {
  name: 'Locate',
  data() {
    return {
      showType: 'equipment', // equipment, supply 或 fault
      chartType: 'bar', // bar 或 pie
      // 月故障率数据
      monthlyFaultRateData: [],
      // 品牌型号级联选择器数据
      selectedBrandModel: [],
      brandModelOptions: [],
      equipmentData: {},
      supplyData: {},
      faultRateData: {
        monthlyFaults: 0,
        totalEquipment: 0,
        faultRate: 0
      },
      brandFaultData: [],
      faultTypeData: [],
      chartInstance: null,
      faultRateChartInstance: null,
      brandFaultChartInstance: null,
      faultTypeChartInstance: null,
      monthlyFaultRateChartInstance: null, // 添加缺失的实例
      dataLoaded: false // 数据加载状态标志
    };
  },
  mounted() {
    // 在mounted中不立即初始化图表，而是等待数据加载完成
  },
  beforeDestroy() {
    this.disposeAllCharts();
  },
  watch: {
    showType() {
      this.handleShowTypeChange();
    },
    chartType() {
      this.updateMainChart();
    }
  },
  async created() {
    try {
      // 等待所有数据加载完成
      await this.loadData();
      this.dataLoaded = true;

      // 数据加载完成后初始化图表
      this.$nextTick(() => {
        this.initAllCharts();
      });
    } catch (error) {
      console.error('数据初始化失败:', error);
      // 即使出错也设置dataLoaded为true，避免页面一直loading
      this.dataLoaded = true;
    }
  },
  methods: {
    // 统一的数据加载方法
    async loadData() {
      try {
        // 并行加载所有数据以提高性能
        const [
          brandModelResponse,
          equipmentResponse,
          monthlyFaultRateResponse,
          faultTypeResponse
        ] = await Promise.all([
          getAllAssetBrandAndModelSpec(),
          getEquipmentData(),
          getMonthlyFaultRateData({}), // 传递空对象作为默认参数
          getFaultTypeData({})
        ]);

        // 更新数据
        this.brandModelOptions = brandModelResponse.data;
        this.equipmentData = equipmentResponse.data;
        this.monthlyFaultRateData = monthlyFaultRateResponse.data;
        this.faultTypeData = faultTypeResponse.data;

        console.log("所有数据加载完成");
      } catch (error) {
        console.error('数据加载失败:', error);
        throw error;
      }
    },

    initAllCharts() {
      // 只有在数据加载完成后才初始化图表
      if (!this.dataLoaded) return;

      // 初始化主图表
      if (this.showType !== 'fault') {
        this.initMainChart();
      } else {
        // 初始化故障统计图表实例
        this.initFaultChartInstances();
      }
    },

    initMainChart() {
      if (this.$refs.mainChart) {
        this.chartInstance = echarts.init(this.$refs.mainChart);
        this.updateMainChart();
      }
    },

    initFaultChartInstances() {
      this.$nextTick(() => {
        // 初始化故障类型占比图表
        if (this.$refs.faultTypeChart && !this.faultTypeChartInstance) {
          this.faultTypeChartInstance = echarts.init(this.$refs.faultTypeChart);
        }

        // 初始化月故障率趋势图表
        if (this.$refs.monthlyFaultRateChart && !this.monthlyFaultRateChartInstance) {
          this.monthlyFaultRateChartInstance = echarts.init(this.$refs.monthlyFaultRateChart);
        }

        // 更新图表数据
        this.updateFaultTypeChart();
        this.updateMonthlyFaultRateChart();
      });
    },

    getMonthlyFaultRateOption() {
      // 确保使用正确的数据字段
      const months = this.monthlyFaultRateData.map(item => item.month || item.months);
      const rates = this.monthlyFaultRateData.map(item => item.rate || item.faultRate);

      return {
        title: {
          text: '月故障率趋势统计',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
            color: '#191111'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const param = params[0];
            return `第${param.name}月: ${param.value}%`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: months,
          axisLabel: {
            fontSize: 12,
            color: '#191111'
          },
          axisLine: {
            lineStyle: {
              color: '#191111'
            }
          },
          splitLine: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '故障率',
          nameTextStyle: {
            color: '#191111'
          },
          axisLabel: {
            formatter: '{value}%',
            color: '#191111'
          },
          axisLine: {
            lineStyle: {
              color: '#f00'
            }
          },
          splitLine: {
            show: false
          }
        },
        series: [{
          name: '故障率',
          type: 'line',
          smooth: false,
          lineStyle: {
            color: '#f00',
            width: 2
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(255, 0, 0, 0.3)' },
              { offset: 1, color: 'rgba(255, 0, 0, 0.1)' }
            ])
          },
          data: rates,
          emphasis: {
            focus: 'series'
          }
        }]
      };
    },

    updateMonthlyFaultRateChart() {
      if (!this.monthlyFaultRateChartInstance || !this.dataLoaded) return;
      const option = this.getMonthlyFaultRateOption();
      this.monthlyFaultRateChartInstance.setOption(option, true);
    },

    disposeAllCharts() {
      this.disposeMainChart();
      this.disposeFaultCharts();
    },

    disposeMainChart() {
      if (this.chartInstance) {
        this.chartInstance.dispose();
        this.chartInstance = null;
      }
    },

    disposeFaultCharts() {
      if (this.faultRateChartInstance) {
        this.faultRateChartInstance.dispose();
        this.faultRateChartInstance = null;
      }
      if (this.brandFaultChartInstance) {
        this.brandFaultChartInstance.dispose();
        this.brandFaultChartInstance = null;
      }
      if (this.faultTypeChartInstance) {
        this.faultTypeChartInstance.dispose();
        this.faultTypeChartInstance = null;
      }
      if (this.monthlyFaultRateChartInstance) {
        this.monthlyFaultRateChartInstance.dispose();
        this.monthlyFaultRateChartInstance = null;
      }
    },

    handleShowTypeChange() {
      if (this.showType === 'fault') {
        // 切换到故障统计，销毁主图表
        this.disposeMainChart();
        // 延迟更新故障统计图表，确保 DOM 已渲染
        this.$nextTick(() => {
          this.initFaultChartInstances();
        });
      } else {
        // 切换到设备状态或耗材，销毁故障图表
        this.disposeFaultCharts();
        // 初始化主图表
        this.$nextTick(() => {
          if (!this.chartInstance && this.$refs.mainChart) {
            this.chartInstance = echarts.init(this.$refs.mainChart);
          }
          this.updateMainChart();
        });
      }
    },

    switchShowType(type) {
      this.showType = type;
    },

    switchChartType(type) {
      this.chartType = type;
      this.updateMainChart();
    },

    updateMainChart() {
      if (!this.chartInstance || this.showType === 'fault' || !this.dataLoaded) return;

      const option = this.chartType === 'bar'
        ? this.getBarChartOption()
        : this.getPieChartOption();

      this.chartInstance.setOption(option, true);
    },

    updateFaultTypeChart() {
      if (!this.faultTypeChartInstance || !this.dataLoaded) return;
      const option = this.getFaultTypePieOption();
      this.faultTypeChartInstance.setOption(option, true);
    },

    getBarChartOption() {
      if (this.showType === 'equipment') {
        return this.getEquipmentBarChartOption();
      } else {
        return this.getSupplyBarChartOption();
      }
    },

    getPieChartOption() {
      if (this.showType === 'equipment') {
        return this.getEquipmentPieChartOption();
      } else {
        return this.getSupplyPieChartOption();
      }
    },

    getEquipmentBarChartOption() {
      const departments = Object.keys(this.equipmentData);
      const normalData = departments.map(dept => this.equipmentData[dept]?.normal || 0);
      const repairingData = departments.map(dept => this.equipmentData[dept]?.repairing || 0);
      const pendingScrapData = departments.map(dept => this.equipmentData[dept]?.pendingScrap || 0);
      const scrapedData = departments.map(dept => this.equipmentData[dept]?.scraped || 0);

      return {
        title: {
          text: '各科室设备状态统计',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['正常', '维修中', '待报废', '已报废'],
          top: '10%'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: departments
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '正常',
            type: 'bar',
            stack: '总量',
            emphasis: {
              focus: 'series'
            },
            data: normalData,
            itemStyle: {
              color: '#5470c6'
            }
          },
          {
            name: '维修中',
            type: 'bar',
            stack: '总量',
            emphasis: {
              focus: 'series'
            },
            data: repairingData,
            itemStyle: {
              color: '#91cc75'
            }
          },
          {
            name: '待报废',
            type: 'bar',
            stack: '总量',
            emphasis: {
              focus: 'series'
            },
            data: pendingScrapData,
            itemStyle: {
              color: '#fac858'
            }
          },
          {
            name: '已报废',
            type: 'bar',
            stack: '总量',
            emphasis: {
              focus: 'series'
            },
            data: scrapedData,
            itemStyle: {
              color: '#ee6666'
            }
          }
        ]
      };
    },

    getSupplyBarChartOption() {
      const departments = Object.keys(this.supplyData);
      const glovesData = departments.map(dept => this.supplyData[dept]?.gloves || 0);
      const swabsData = departments.map(dept => this.supplyData[dept]?.swabs || 0);

      return {
        title: {
          text: '各科室耗材数量统计',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['手套', '棉签'],
          top: '10%'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: departments
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '手套',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: glovesData,
            itemStyle: {
              color: '#5470c6'
            }
          },
          {
            name: '棉签',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: swabsData,
            itemStyle: {
              color: '#91cc75'
            }
          }
        ]
      };
    },

    getEquipmentPieChartOption() {
      const departments = Object.keys(this.equipmentData);
      const normalTotal = departments.reduce((sum, dept) => sum + (this.equipmentData[dept]?.normal || 0), 0);
      const repairingTotal = departments.reduce((sum, dept) => sum + (this.equipmentData[dept]?.repairing || 0), 0);
      const pendingScrapTotal = departments.reduce((sum, dept) => sum + (this.equipmentData[dept]?.pendingScrap || 0), 0);
      const scrapedTotal = departments.reduce((sum, dept) => sum + (this.equipmentData[dept]?.scraped || 0), 0);

      return {
        title: {
          text: '设备状态分布统计',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '设备状态',
            type: 'pie',
            radius: '50%',
            data: [
              { value: normalTotal, name: '正常', itemStyle: { color: '#5470c6' } },
              { value: repairingTotal, name: '维修中', itemStyle: { color: '#91cc75' } },
              { value: pendingScrapTotal, name: '待报废', itemStyle: { color: '#fac858' } },
              { value: scrapedTotal, name: '已报废', itemStyle: { color: '#ee6666' } }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
    },

    getSupplyPieChartOption() {
      const departments = Object.keys(this.supplyData);
      const glovesTotal = departments.reduce((sum, dept) => sum + (this.supplyData[dept]?.gloves || 0), 0);
      const swabsTotal = departments.reduce((sum, dept) => sum + (this.supplyData[dept]?.swabs || 0), 0);

      return {
        title: {
          text: '耗材数量分布统计',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '耗材数量',
            type: 'pie',
            radius: '50%',
            data: [
              { value: glovesTotal, name: '手套', itemStyle: { color: '#5470c6' } },
              { value: swabsTotal, name: '棉签', itemStyle: { color: '#91cc75' } }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
    },

    getFaultTypePieOption() {
      const data = this.faultTypeData.map(item => ({
        value: item.percentage || item.rate,
        name: `${item.faultType || item.type} ${item.percentage || item.rate}%`
      }));

      return {
        title: {
          text: '故障类型占比',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}%'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'middle'
        },
        series: [
          {
            name: '故障类型',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data
          }
        ]
      };
    },

    getRankClass(rank) {
      switch (rank) {
        case 1: return 'rank-1';
        case 2: return 'rank-2';
        case 3: return 'rank-3';
        default: return '';
      }
    },

    filterByBrandModel() {
      const params = {};
      console.log('filterByBrandModel', this.selectedBrandModel)
      // console.log('filterByBrandModel', this.se)
      if (this.selectedBrandModel && this.selectedBrandModel.length > 0) {
        if (this.selectedBrandModel.length === 1) {
          params.brand = this.selectedBrandModel[0];
        } else if (this.selectedBrandModel.length === 2) {
          params.brand = this.selectedBrandModel[0];
          params.model = this.selectedBrandModel[1];
        }
      }

      // 重新获取月故障率数据
      getMonthlyFaultRateData(params).then(response => {
        this.monthlyFaultRateData = response.data;
        this.updateMonthlyFaultRateChart();
      }).catch(error => {
        console.error('获取月故障率数据失败:', error);
      });

      // 重新获取故障类型数据
      getFaultTypeData( params).then(response => {
        this.faultTypeData = response.data;
        this.updateFaultTypeChart();
      }).catch(error => {
        console.error('获取故障类型数据失败:', error);
      });
    }
  }
};
</script>

<style scoped>
.chart-container {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.control-panel {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 15px;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.control-group {
  display: flex;
  align-items: center;
}

.control-label {
  margin-right: 10px;
  font-weight: bold;
  color: #606266;
}

.chart-wrapper {
  padding: 15px;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  min-height: 500px;
  position: relative;
}

.chart {
  width: 100%;
  height: 500px;
}

/* 故障统计样式 */
.fault-statistics-container {
  width: 100%;
}

.fault-statistics-container h3 {
  margin: 20px 0 15px 0;
  color: #303133;
  font-size: 18px;
  font-weight: bold;
}

.fault-rate-section,
.brand-fault-section,
.fault-type-section {
  margin-bottom: 30px;
}

.fault-rate-chart {
  width: 100%;
  height: 400px;
}

.brand-fault-content {
  display: flex;
  gap: 20px;
}

.brand-fault-chart {
  flex: 1;
  height: 400px;
}

.brand-fault-table {
  flex: 1;
  min-width: 500px;
}

.fault-type-chart {
  width: 100%;
  height: 500px;
}

.rank-1 {
  color: #ffd700;
  font-weight: bold;
  font-size: 16px;
}

.rank-2 {
  color: #c0c0c0;
  font-weight: bold;
  font-size: 16px;
}

.rank-3 {
  color: #cd7f32;
  font-weight: bold;
  font-size: 16px;
}

.monthly-fault-rate-section {
  margin-bottom: 30px;
}

.monthly-fault-rate-chart {
  width: 100%;
  height: 400px;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 500px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@media (max-width: 1200px) {
  .brand-fault-content {
    flex-direction: column;
  }

  .brand-fault-table {
    min-width: auto;
  }
}
</style>
